import React, { useEffect, useState } from 'react';
import { Breadcrumb, Select } from 'antd';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { fetchUnitList } from '../../services/unit';
import './Topbar.less';

const { Option } = Select;

const Topbar: React.FC = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const { unitId } = useParams();
    const [unitList, setUnitList] = useState<any[]>([]);
    const [currentUnit, setCurrentUnit] = useState<any>(null);
    const [appList, setAppList] = useState<any[]>([]); // 应用列表

    // 拉取所有单元用于切换
    useEffect(() => {
        if (location.pathname.startsWith('/unit/')) {
            fetchUnitList({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
                const data = res.data || res;
                const units = data.records || [];
                setUnitList(units);
                // 找到当前单元
                const current = units.find((u: any) => u.unitId === unitId);
                setCurrentUnit(current);

                // 提取所有唯一的应用ID
                const uniqueApps = Array.from(new Set(units.map((u: any) => u.appId).filter(Boolean)))
                    .map(appId => ({
                        appId,
                        units: units.filter((u: any) => u.appId === appId)
                    }));
                console.log('所有应用列表:', uniqueApps);
                console.log('总单元数:', units.length);
                setAppList(uniqueApps);
            });
        }
    }, [location.pathname, unitId]);

    // 路由解析
    let crumbs: Array<{ label: string; path?: string; isUnitId?: boolean; isAppId?: boolean }> = [
        { label: '工作台', path: '/units' }
    ];
    if (location.pathname === '/units') {
        crumbs.push({ label: '单元管理', path: '/units' });
    } else if (/^\/unit\/([^/]+)$/.test(location.pathname)) {
        // 添加应用ID面包屑
        if (currentUnit?.appId) {
            crumbs.push({ label: currentUnit.appId, isAppId: true });
        }
        crumbs.push({ label: unitId || '', path: `/unit/${unitId}`, isUnitId: true });
        crumbs.push({ label: '单元详情' });
    } else if (/^\/unit\/([^/]+)\/edit$/.test(location.pathname)) {
        if (currentUnit?.appId) {
            crumbs.push({ label: currentUnit.appId, isAppId: true });
        }
        crumbs.push({ label: unitId || '', path: `/unit/${unitId}`, isUnitId: true });
        crumbs.push({ label: '编辑单元' });
    } else if (/^\/unit\/([^/]+)\/info$/.test(location.pathname)) {
        if (currentUnit?.appId) {
            crumbs.push({ label: currentUnit.appId, isAppId: true });
        }
        crumbs.push({ label: unitId || '', path: `/unit/${unitId}`, isUnitId: true });
        crumbs.push({ label: '单元信息' });
    } else if (/^\/unit\/([^/]+)\/methods$/.test(location.pathname)) {
        if (currentUnit?.appId) {
            crumbs.push({ label: currentUnit.appId, isAppId: true });
        }
        crumbs.push({ label: unitId || '', path: `/unit/${unitId}`, isUnitId: true });
        crumbs.push({ label: '方法清单' });
    }
    return (
        <div className="topbar-container">
            <Breadcrumb className="breadcrumb-wrapper" separator={<span style={{ margin: '0 8px', color: '#d9d9d9' }}>/</span>}>
                {crumbs.map((c, i) => {
                    // 应用ID面包屑 - 支持检索和切换
                    if (c.isAppId && currentUnit?.appId) {
                        return (
                            <Breadcrumb.Item key={`app-${c.label}`}>
                                <Select
                                    className="app-select"
                                    dropdownStyle={{ fontSize: 14, maxWidth: 400 }}
                                    value={currentUnit.appId}
                                    onChange={val => {
                                        // 切换到该应用下的第一个单元
                                        const targetApp = appList.find((app: any) => app.appId === val);
                                        if (targetApp && targetApp.units.length > 0) {
                                            navigate(`/unit/${targetApp.units[0].unitId}`);
                                        }
                                    }}
                                    placeholder="选择应用"
                                    showSearch
                                    bordered={false}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => {
                                        if (!input) return true;
                                        const searchText = input.toLowerCase();
                                        const appIdMatch = (option?.value as string || '').toLowerCase().includes(searchText);
                                        const labelMatch = (option?.label as string || '').toLowerCase().includes(searchText);
                                        return appIdMatch || labelMatch;
                                    }}
                                >
                                    {appList.map((app: any) => (
                                        <Option
                                            key={app.appId}
                                            value={app.appId}
                                            label={app.appId}
                                        >
                                            {app.appId}
                                        </Option>
                                    ))}
                                </Select>
                            </Breadcrumb.Item>
                        );
                    }

                    // 单元ID面包屑 - 只显示当前应用下的单元
                    if (c.isUnitId && unitId) {
                        // 过滤出当前应用下的单元
                        const filteredUnits = currentUnit?.appId
                            ? unitList.filter((u: any) => u.appId === currentUnit.appId)
                            : unitList;

                        return (
                            <Breadcrumb.Item key={c.label}>
                                <Select
                                    className="unit-select"
                                    dropdownStyle={{ fontSize: 14, maxWidth: 500 }}
                                    value={unitId}
                                    onChange={val => navigate(`/unit/${val}`)}
                                    placeholder="单元ID"
                                    showSearch
                                    bordered={false}
                                    optionLabelProp="label"
                                    filterOption={(input, option) => {
                                        const unitIdMatch = (option?.value as string || '').toLowerCase().includes(input.toLowerCase());
                                        const unitNameMatch = (option?.label as string || '').toLowerCase().includes(input.toLowerCase());
                                        return unitIdMatch || unitNameMatch;
                                    }}
                                >
                                    {filteredUnits.map((u: any) => (
                                        <Option
                                            key={u.unitId}
                                            value={u.unitId}
                                            label={u.unitName || u.unitId}
                                        >
                                            <div className="option-item">
                                                <div className="option-title">
                                                    {u.unitName || u.unitId}
                                                </div>
                                                {u.unitName && (
                                                    <div className="option-subtitle">
                                                        单元ID: {u.unitId}
                                                    </div>
                                                )}
                                            </div>
                                        </Option>
                                    ))}
                                </Select>
                            </Breadcrumb.Item>
                        );
                    }

                    // 普通链接面包屑
                    if (c.path && i !== crumbs.length - 1) {
                        return (
                            <Breadcrumb.Item key={c.label}>
                                <a
                                    href={c.path}
                                    onClick={e => {
                                        e.preventDefault();
                                        navigate(c.path!);
                                    }}
                                    style={{ color: '#1677ff', fontSize: 16, padding: 0, margin: 0 }}
                                >
                                    {c.label}
                                </a>
                            </Breadcrumb.Item>
                        );
                    }

                    // 普通文本面包屑
                    return <Breadcrumb.Item key={c.label}>{c.label}</Breadcrumb.Item>;
                })}
            </Breadcrumb>
        </div>
    );
};

export default Topbar; 